package xworker.lang.task.state;

import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.lang.executor.Executor;

public class StateTask {
    private static final String TAG = StateTask.class.getName();

    String state;
    Thing thing;
    ActionContext actionContext;

    public StateTask(Thing thing, ActionContext parentContext){
        this.thing = thing;
        this.actionContext = parentContext;
    }

    public void setState(String state){
        if(state == null || state.isEmpty()){
            Executor.debug(TAG, "Can not set new state, state is null or empty, thing={}", thing.getMetadata().getPath());
            return;
        }

        this.state = state;
        for(Thing child : thing.getChilds()){
            if(child.getMetadata().getName().equals(state)){
                Executor.debug(TAG, "Execute state {}", child.getMetadata().getPath());
                child.getAction().run(actionContext);

                return;
            }
        }
    }

    public static StateTask run(ActionContext actionContext){
        Thing self = actionContext.getObject("self");

        StateTask task = new StateTask(self, actionContext);
        String initialState = self.doAction("getInititalState", actionContext);
        if(initialState != null){
            task.setState(initialState);
        }

        return task;
    }
}
